from wtforms.form import Form
from wtforms.fields.core import StringField, IntegerField
from wtforms.validators import DataRequired, length, Email, Regexp, ValidationError
from app.libs.enums import ClientTypeEnum
from app.models.user import User
from app.validators.base import MyBaseForm

#客户端表单(数据属性定义)
class ClientForm(MyBaseForm):
    account = StringField(validators=[DataRequired(message='不允许为空'),
                                      length(min=5, max=32)])
    secret = StringField()
    #注册用户的形式类型(手机号，邮箱,....)
    reg_type = IntegerField(validators=[DataRequired()])
    
    #注意这里函数名是要根据要校验的属性名而改写的，格式为validate_XXX， 如:validate_reg_type
    def validate_reg_type(self, field):
        try:
            #注意枚举类型取数据要用.data
            client = ClientTypeEnum(field.data)
        except ValueError:
            raise ValidationError('客户端类型不符合要求')
        self.reg_type.data = client
        
        
class UserEmailForm(ClientForm):
    account = StringField(validators=[Email(message='invalidate email')])
    
    secret = StringField(validators=[DataRequired(),
                                     #password can only include letters, numbers and "_"
                                     Regexp(r'^[A-Za-z0-9_*&$#@$]{6,22}')])
    nickname = StringField(validators=[DataRequired(),
                                       length(min=2, max=22)])
    
    def validate_account(self, value):
        if User.query.filter_by(email=value.data).first():
            raise ValidationError('该电子邮件已被注册')
        
        